<template>
  <div class="user-cert-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.params.userName"
        placeholder="用户姓名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.params.examTitle"
        placeholder="考试名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.params.status"
        placeholder="证书状态"
        clearable
        style="width: 150px"
        class="filter-item"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        class="filter-item"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        icon="el-icon-upload2"
        @click="handleBatchGenerate"
      >
        批量生成
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column 
        label="ID" 
        prop="id" 
        align="center" 
        width="100" 
      />
      <el-table-column
        label="用户姓名"
        align="center"
        width="120"
      >
        <template slot-scope="{row}">
          {{ row.userName }}
        </template>
      </el-table-column>
      <el-table-column
        label="考试名称"
        align="center"
        min-width="150"
        prop="examTitle"
      />
      <el-table-column
        label="证书名称"
        align="center"
        min-width="150"
        prop="certTitle"
      />
      <el-table-column
        label="考试成绩"
        align="center"
        width="120"
      >
        <template slot-scope="{row}">
          <span>{{ row.userScore || '0' }}分</span>
          <el-divider direction="vertical" />
          <span>及格: {{ row.qualifyScore || '0' }}分</span>
        </template>
      </el-table-column>
      <el-table-column
        label="考试时间"
        align="center"
        width="160"
        prop="examTime"
      />
      <el-table-column
        label="证书状态"
        align="center"
        width="120"
      >
        <template slot-scope="{row}">
          <el-tag :type="getCertStatusType(row.status)">
            {{ getCertStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="生成时间"
        align="center"
        width="160"
        prop="generateTime"
      />
      <el-table-column
        label="操作"
        align="center"
        width="220"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button
            :disabled="row.status !== 2"
            type="primary"
            size="mini"
            @click="handleView(row)"
          >
            查看证书
          </el-button>
          <el-button
            v-if="row.status === 0 || row.status === 3"
            type="warning"
            size="mini"
            @click="handleGenerate(row)"
          >
            重新生成
          </el-button>
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <!-- 证书预览对话框 -->
    <el-dialog 
      title="证书预览" 
      :visible.sync="dialogPreviewVisible"
      width="80%"
      fullscreen
      center
    >
      <div class="certificate-preview" v-loading="previewLoading">
        <iframe v-if="currentCert && currentCert.certUrl" :src="currentCert.certUrl" class="certificate-iframe"></iframe>
        <div v-else class="no-certificate">
          <i class="el-icon-document"></i>
          <p>证书文件不存在或无法访问</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogPreviewVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 批量生成对话框 -->
    <el-dialog 
      title="为考试通过的用户批量生成证书" 
      :visible.sync="dialogBatchVisible"
      width="600px"
    >
      <el-form :model="batchForm" label-width="100px" :rules="batchRules" ref="batchForm">
        <el-form-item label="选择考试" prop="examId">
          <el-select
            v-model="batchForm.examId"
            filterable
            placeholder="请选择考试"
            style="width: 100%"
          >
            <el-option
              v-for="item in examList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBatchVisible = false">取 消</el-button>
        <el-button type="primary" :loading="batchLoading" @click="confirmBatchGenerate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量删除对话框 -->
    <el-dialog 
      title="批量删除证书" 
      :visible.sync="dialogBatchDeleteVisible"
      width="600px"
    >
      <el-form :model="batchDeleteForm" label-width="100px" :rules="batchDeleteRules" ref="batchDeleteForm">
        <el-form-item label="删除方式" prop="deleteType">
          <el-radio-group v-model="batchDeleteForm.deleteType">
            <el-radio label="selected">删除选中的证书 ({{ multipleSelection.length }}个)</el-radio>
            <el-radio label="byExam">删除指定考试的所有证书</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          v-if="batchDeleteForm.deleteType === 'byExam'" 
          label="选择考试" 
          prop="examId"
        >
          <el-select
            v-model="batchDeleteForm.examId"
            filterable
            placeholder="请选择考试"
            style="width: 100%"
          >
            <el-option
              v-for="item in examList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="delete-warning">
        <i class="el-icon-warning" style="color: #E6A23C;"></i>
        <span>删除操作不可恢复，请谨慎操作！</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBatchDeleteVisible = false">取 消</el-button>
        <el-button type="danger" :loading="batchDeleteLoading" @click="confirmBatchDelete">确认删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { fetchPaging, manualGenerate, createCertTasks, deleteUserCertificate, deleteAllCertificatesByExam } from '@/api/user/cert'
import { fetchList as fetchExamList } from '@/api/exam/exam'
import Pagination from '@/components/Pagination'

export default {
  name: 'UserCertificateList',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        params: {
          userName: '',
          examTitle: '',
          status: ''
        }
      },
      statusOptions: [
        { label: '待生成', value: 0 },
        { label: '生成中', value: 1 },
        { label: '已生成', value: 2 },
        { label: '生成失败', value: 3 }
      ],
      dialogPreviewVisible: false,
      dialogBatchVisible: false,
      dialogBatchDeleteVisible: false,
      previewLoading: false,
      batchLoading: false,
      batchDeleteLoading: false,
      currentCert: null,
      examList: [],
      multipleSelection: [],
      batchForm: {
        examId: ''
      },
      batchRules: {
        examId: [{ required: true, message: '请选择考试', trigger: 'change' }]
      },
      batchDeleteForm: {
        deleteType: 'selected',
        examId: ''
      },
      batchDeleteRules: {
        examId: [{ required: true, message: '请选择考试', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      console.log('开始加载证书列表，查询参数：', this.listQuery)
      fetchPaging(this.listQuery).then(response => {
        console.log('证书列表加载成功：', response)
        this.list = response.data.records || []
        this.total = response.data.total || 0
        this.listLoading = false
      }).catch(error => {
        console.error('证书列表加载失败：', error)
        this.$message.error('加载证书列表失败：' + (error.message || '未知错误'))
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    getCertStatusType(status) {
      const statusMap = {
        0: 'info',    // 待生成
        1: 'warning', // 生成中
        2: 'success', // 已生成
        3: 'danger'   // 生成失败
      }
      return statusMap[status] || 'info'
    },
    getCertStatusLabel(status) {
      const statusMap = {
        0: '待生成',
        1: '生成中',
        2: '已生成',
        3: '生成失败'
      }
      return statusMap[status] || '未知状态'
    },
    handleView(row) {
      this.currentCert = row
      this.dialogPreviewVisible = true
      this.previewLoading = true
      
      // 如果需要刷新证书URL，可以在这里添加请求
      setTimeout(() => {
        this.previewLoading = false
      }, 1000)
    },

    handleGenerate(row) {
      this.$confirm('确认重新生成该证书?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        manualGenerate(row.userId, row.examId, row.certId).then(() => {
          this.$message({
            type: 'success',
            message: '证书生成任务已提交!'
          })
          this.getList() // 刷新列表
        })
      }).catch(() => {
        // 取消操作
      })
    },
    handleBatchGenerate() {
      this.dialogBatchVisible = true
      this.batchForm.examId = ''
      
      // 加载考试列表
      this.loadExamList()
    },
    loadExamList() {
      fetchExamList().then(response => {
        this.examList = response.data.records || response.data || []
      })
    },
    confirmBatchGenerate() {
      this.$refs.batchForm.validate(valid => {
        if (valid) {
          this.batchLoading = true
          
          createCertTasks(this.batchForm.examId).then(() => {
            this.$message({
              type: 'success',
              message: '批量证书生成任务已提交!'
            })
            this.dialogBatchVisible = false
            this.batchLoading = false
            this.getList() // 刷新列表
          }).catch(() => {
            this.batchLoading = false
          })
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDelete(row) {
       this.$confirm(`确认删除用户"${row.userName}"的"${row.examTitle}"证书?`, '删除确认', {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       }).then(() => {
         deleteUserCertificate(row.userId, row.examId, row.certId).then(() => {
           this.$message({
             type: 'success',
             message: '证书删除成功!'
           })
           this.getList() // 刷新列表
         }).catch(error => {
           this.$message.error('删除失败：' + (error.message || '未知错误'))
         })
       }).catch(() => {
         // 取消操作
       })
     },
    handleBatchDelete() {
      this.dialogBatchDeleteVisible = true
      this.batchDeleteForm.deleteType = 'selected'
      this.batchDeleteForm.examId = ''
      
      // 加载考试列表
      this.loadExamList()
    },
    confirmBatchDelete() {
      this.$refs.batchDeleteForm.validate(valid => {
        if (valid || this.batchDeleteForm.deleteType === 'selected') {
          if (this.batchDeleteForm.deleteType === 'selected') {
            if (this.multipleSelection.length === 0) {
              this.$message.warning('请先选择要删除的证书')
              return
            }
            
            this.$confirm(`确认删除选中的 ${this.multipleSelection.length} 个证书?`, '批量删除确认', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.batchDeleteLoading = true
              
              // 批量删除选中的证书
               const deletePromises = this.multipleSelection.map(cert => 
                 deleteUserCertificate(cert.userId, cert.examId, cert.certId)
               )
              
              Promise.all(deletePromises).then(() => {
                this.$message({
                  type: 'success',
                  message: '批量删除成功!'
                })
                this.dialogBatchDeleteVisible = false
                this.batchDeleteLoading = false
                this.getList() // 刷新列表
              }).catch(error => {
                this.$message.error('批量删除失败：' + (error.message || '未知错误'))
                this.batchDeleteLoading = false
              })
            })
          } else if (this.batchDeleteForm.deleteType === 'byExam') {
            const selectedExam = this.examList.find(exam => exam.id === this.batchDeleteForm.examId)
            const examTitle = selectedExam ? selectedExam.title : '未知考试'
            
            this.$confirm(`确认删除考试"${examTitle}"的所有证书?`, '批量删除确认', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.batchDeleteLoading = true
              
              deleteAllCertificatesByExam(this.batchDeleteForm.examId).then(() => {
                this.$message({
                  type: 'success',
                  message: '批量删除成功!'
                })
                this.dialogBatchDeleteVisible = false
                this.batchDeleteLoading = false
                this.getList() // 刷新列表
              }).catch(error => {
                this.$message.error('批量删除失败：' + (error.message || '未知错误'))
                this.batchDeleteLoading = false
              })
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.user-cert-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}

.certificate-preview {
  width: 100%;
  height: 70vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.certificate-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.no-certificate {
  text-align: center;
  color: #909399;
}

.no-certificate i {
  font-size: 50px;
  margin-bottom: 10px;
}

.delete-warning {
  margin: 15px 0;
  padding: 10px;
  background-color: #fdf6ec;
  border: 1px solid #faecd8;
  border-radius: 4px;
  color: #E6A23C;
}

.delete-warning i {
  margin-right: 8px;
}
</style>